package sendandreceive;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;



public class Server{
	
	static ObjectOutputStream os = null;
	static Socket server = null;
	static ServerSocket s;
	static ObjectInputStream is = null;
	static DataInputStream dis = null;
	static String msgs;
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		String host = "127.0.0.1"; int port = 6000;
		s = new ServerSocket(6000);
		//server = s.accept();
		while (true){
			openConect();	
			receive();
			send(); 		
		}
		}
	static void openConect(){
		try {
			server = s.accept();
			System.out.println("CONNECTED");
			is = new ObjectInputStream(server.getInputStream());
			os = new ObjectOutputStream(server.getOutputStream());		
		} catch (IOException e) {
			e.printStackTrace();
		}			
	}	
	static void receive(){
		try {		
			String msg = (String)is.readObject();
			System.out.println(msg);		
			if (msg.length() ==0){
				System.out.println("Close socket : " + server.getInetAddress());
				is.close();
				os.close();
			}				
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}	
	static void send() {
				dis  = new DataInputStream(System.in);
				try {
					msgs = dis.readLine();
					os.writeObject("Server :"+msgs);
					os.flush();
					System.out.println("Server :"+msgs);
				} catch (IOException e) {
				System.out.println("Conexao cliente perdida : "+ server.getRemoteSocketAddress());
					e.printStackTrace();
				}				
	}
	private static void closeConnection() throws IOException
	{	
		os.close();
		is.close();	
	}



}
	
	
	
	
	